package coderead.maven.search;


import coderead.maven.bean.ArtifactIndexInfo;
import lombok.Data;

import java.io.Serializable;

/**
 * @author Tommy
 * Created by Tommy on 2019/10/30
 **/
@Data
public class SearchResult implements Serializable {

    private static final long serialVersionUID = -4952875497756693403L;

    // 高亮显示命中字符
    private int[] highlight;
    private String highlightText;

    // 最后匹配的词
    private transient WordIndex mathIndex;
    private ArtifactIndexInfo item;

    public SearchResult(ArtifactIndexInfo item) {
        this.item = item;
    }

    // r1 r2
    public int compareTo(SearchResult target) {
        if (target == this || target.item == this.item) {
            return 0;
        }

        // 热度越高越靠前
        int result = target.item.hot - this.item.hot;

        // 匹配越靠左,越靠前
        if (result == 0) {
            result = this.mathIndex.getIndex() - target.mathIndex.getIndex();
        }
        // dubbo-qos
        // 字符越短，越靠前
        if (result == 0) {
            result = this.item.artifactId.length() - target.item.artifactId.length();
        }
        // 数字越短，级别越高
        if (result == 0) {
            result = getGroupLive(this.item.groupId) - getGroupLive(target.item.groupId);
        }
        // 更新时间越近，越靠前
        if (result == 0) {
            result = target.item.lastModified > this.item.lastModified ? 1 : -1;
        }
        return result;
    }

    private int getGroupLive(String groupId) {
        for (int i = 0; i < groupIds.length; i++) {
            if (groupId.startsWith(groupIds[i])) {
                return i;
            }
        }
        return groupIds.length;
    }

    private final static String[] groupIds = {"org.apache", "org.springframework", "org"};

}
